import router from '../router/index';
import axios from 'axios';
import qs from 'qs';
import { MessageBox } from 'element-ui';

let cancel = false;
// var BASE_URL = 'http://192.168.2.89:8080/';
// var BASE_URL = 'http://192.168.1.74/';
// var BASE_URL = 'http://192.168.1.99/';
// var BASE_URL = 'http://192.168.1.240:9527/';
var BASE_URL = 'http://192.168.2.71:80/chengben_api/';
let http = axios.create({
    baseURL: process.env.NODE_ENV === 'development' ? '' : BASE_URL,
    // 跨域请求时是否需要使用凭证
    withCredentials: true,
    // 即将被发送的自定义请求头
    timeout: 10000
});
// console.log(baseURL)
//添加请求拦截器
http.interceptors.request.use(
    config => {
        // if (localStorage.getItem('token')) {
        //     config.headers.common['Authorization'] = localStorage.getItem('token');
        // }
        return config;
    },
    error => {

        return Promise.reject(error);
    }
);

//添加响应拦截器
http.interceptors.response.use(
    res => {
        if (res.data.code === 401 && !cancel) {
            MessageBox.alert('登录信息过期,请重新登录!', '登录超时', {
                confirmButtonText: '去登录',
                callback: action => {
                    router.replace({
                        path: '/login'
                        // query: {redirect: '/login'}
                    });
                    localStorage.clear();
                    return Promise.reject(new Error('token expired'));
                }
            });
            cancel = true;
            return Promise.reject(res.data);
        } else {
            res.request.responseURL.search('/login-center/login') ? cancel = false : ''
            return res;
        }
    },
    error => {
        console.log('登录超时');
        const response = { data: { code: -1 } };
        return response;
    }
);
//路由拦截器
// http.interceptors.response.use(
//   response => {
//     // debugger
//     console.log(response.data.code)
//     if (response.data.code == 108) {
//         // this.$message('请重新登录')
//         router.replace({
//           path:'/login',
//           // query: {redirect: '/login'}
//         })
//         localStorage.clear();
//         return Promise.reject(new Error('token expired'))
//       }
//      else {
//       return response
//     }})
//发送post请求
export function post(url, params) {
    http.defaults.headers['Authorization'] = localStorage.getItem('token')
    return new Promise((resolve, reject) => {
        http.defaults.headers.post['Content-Type'] = 'application/json';
        http.post(url, params)
            .then(
                response => {
                    resolve(response.data);
                },
                err => {
                    reject(err);
                }
            )
            .catch(error => {
                reject(error);
            });
    });
}

//发送get请求
export function get(url, param) {
    http.defaults.headers['Authorization'] = localStorage.getItem('token')
    return new Promise((resolve, reject) => {
        http.get(url, {
            params: param
        })
            .then(
                response => {
                    resolve(response.data);
                },
                err => {
                    reject(err);
                }
            )
            .catch(error => {
                reject(error);
            });
    });
}

//发送post请求（表单格式）
export function formPost(url, params) {
    http.defaults.headers['Authorization'] = localStorage.getItem('token')
    return new Promise((resolve, reject) => {
        http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
        http.post(url, qs.stringify(params))
            .then(
                response => {
                    resolve(response.data);
                },
                err => {
                    reject(err);
                }
            )
            .catch(error => {
                reject(error);
            });
    });
}
export {
    BASE_URL
}
